local AT2_UI2

local function AT2_IsSecure()
	AT2_Print(debugstack(2, 1, 1),"debug","AT2_IsSecure")
	if (debugstack(2,1,1):find("Interface\\AddOns\\AutoTalker2\\")) then
		return true
	else
		return false
	end
end

function AT2()
	if (AT2_IsSecure()) then
		return AT2_UI2
	else
		return nil --error("This function can only called by AutoTalker2 itself!")
	end
end


function AT2_GetParent(object)
	if (AT2_IsSecure()) then
		return object:GetParent()
	else
		return nil
	end
end


function AT2_UI_Init()
	if not AT2_UI_InitDone then
		AT2_Print("Initializing UI","debug","AT2_UI_Init")
		--main stuff
		AT2_UI2=CreateFrame("Frame",nil,WorldFrame) -- ToDo: Rename to AT2_UI from AT2_UI2 after constructing and testing


		AT2_UI_UIEvents={}
		AT2_UI2.frames=AT2_UI2.frames or {}
		AT2_UI2.fname="!AT2_UI2"
		AT2_UI2:SetScript("OnEnter",function() AT2_ShowTooltip2(AT2_UI2) end)
		AT2_UI2:SetScript("OnLeave",function() AT2_ShowTooltip2() end)
		AT2_UI2.Fonts={}
		AT2_UI2.Fonts["Enigmatic"]=CreateFont("Enigmatic")
		AT2_UI2.Fonts["Enigmatic"]:SetFont("Interface\\AddOns\\AutoTalker2\\Fonts\\EnigmaU_2.TTF",12,"OUTLINE")
		AT2_UI2.Fonts["EnigmaticSmall"]=CreateFont("EnigmaticSmall")
		AT2_UI2.Fonts["EnigmaticSmall"]:SetFont("Interface\\AddOns\\AutoTalker2\\Fonts\\EnigmaU_2.TTF",11,"OUTLINE")
		AT2_UI2.Fonts["YanoneKaffeesatz-Light"]=CreateFont("YanoneKaffeesatz-Light")
		AT2_UI2.Fonts["YanoneKaffeesatz-Light"]:SetFont("Interface\\AddOns\\AutoTalker2\\Fonts\\YanoneKaffeesatz-Light.ttf",18)
		AT2_UI2.LinesCounter=0 -- hah, shitty method
		
		AT2_UI2:SetToplevel(true)
		AT2_UI2:SetFrameStrata("DIALOG")
		AT2_UI2:EnableMouse(true)
		AT2_UI2:SetMovable(true)
		AT2_UI2:SetResizable(true)
		AT2_UI2:SetWidth(486)
		AT2_UI2:SetMinResize(486,38)
		
		AT2_UI2:SetHeight(38)
		AT2_UI2:SetBackdrop({bgFile="Interface\\BUTTONS\\WHITE8X8",tile=false,edgeFile="Interface\\BUTTONS\\WHITE8X8",edgeSize=1})
		AT2_UI2:SetBackdropColor(0, 0, 0, .65)
		AT2_UI2:SetPoint("CENTER",WorldFrame,"CENTER")
		AT2_UI2:SetScript("OnSizeChanged",function() AT2_UI_OnResize() end)
		AT2_UI2:Hide()

		local closeButton=AT2_UI_CreateButton({parent=AT2_UI2,name="AT2_UI_Close",text="X",point="TOPRIGHT",posX=-1,posY=-1,relativePoint="TOPRIGHT"}) 
		AT2_UI2_AddUIEvent(closeButton,"OnClick",function() AT2_UI2:Hide() end)
		tinsert(AT2_UI2.frames,closeButton)
		AT2_UI_CreateLine(closeButton,nil,nil,1,19,"LEFT")


		--header
		tinsert(AT2_UI2.frames,AT2_UI_CreateLine(AT2_UI2,nil,-19,AT2_UI2:GetWidth(),1,"TOP"))
		local title=AT2_UI_CreateFontString(AT2_UI2,"addontitle","YanoneKaffeesatz-Light","TOP",nil,-2)
		title:SetText("\124cff71D5FF\A\124r\124cff0070DD\uto\124r\124cff71D5FF\T\124r\124cff0070DDalker\124r\124cffFFFF33 "..GetAddOnMetadata("AutoTalker2","version").." /ui-lua")

		--stacked stuff
		--Message editor stack
		local messageStack=AT2_UI_CreateStack(AT2_UI2,"messageStack")
		local messageStack_label=AT2_UI_CreateFontString(messageStack,"messageStack_label","EnigmaticSmall","LEFT",4,1)
		messageStack_label:SetText("Üzenet (0/250)")
		local messageStack_SendButton=AT2_UI_CreateButton({parent=messageStack,name="AT2_UI_StartStop",text="Indítás",point="RIGHT",posX=-1,posY=1,relativePoint="RIGHT"})
		AT2_UI2_AddUIEvent(messageStack_SendButton,"OnClick",function() AT2_Print("ToDo: Implement this!!","error") end)
		tinsert(messageStack,AT2_UI_CreateLine(messageStack_SendButton,nil,nil,1,19,"LEFT"))
		local messageStack_editbox=AT2_UI_CreateEditBox({parent=messageStack,name="AT2_UI_MessageEditBox","LEFT",point=messageStack_label:GetStringWidth()+2,width=messageStack:GetWidth()-(messageStack_SendButton:GetWidth()+messageStack_label:GetStringWidth()+2),relativePoint="LEFT",hint="Ide írd az üzenetet"})
		messageStack_editbox.specialAutoSize=function() return messageStack:GetWidth()-(messageStack_SendButton:GetWidth()+messageStack_label:GetStringWidth()+2) end
		messageStack_editbox:SetMaxBytes(250)
		--[[
		local messageStack_editboxHint=AT2_UI_CreateFontString(messageStack_editbox,"messageStack_editboxHint","Enigmatic","LEFT",4,0)
		messageStack_editboxHint:SetText(AT2_StringFormat("•grayIde írd az üzenetet•xc"))
		AT2_UI2_AddUIEvent(messageStack_editbox,"OnEditFocusGained",function() messageStack_editboxHint:Hide() end)
		AT2_UI2_AddUIEvent(messageStack_editbox,"OnEditFocusLost",function() if (messageStack_editbox:GetText():len()==0) then messageStack_editboxHint:Show() end end)
		]]

		--Channel settings stack
		local channelStack=AT2_UI_CreateStack(AT2_UI2,"channelStack")
		local channelStack_label=AT2_UI_CreateFontString(channelStack,"channelStack_label","EnigmaticSmall","LEFT",4,1)
		channelStack_label:SetText("Csatorna")
		tinsert(channelStack,AT2_UI_CreateLine(channelStack,channelStack_label:GetStringWidth()+2,nil,1,19,"LEFT"))
		local guildRadioButton=AT2_UI_CreateRadioButton({parent=channelStack,name="guildRadioButton",text="Guild",posX=channelStack_label:GetStringWidth()+6,point="LEFT",relativePoint="LEFT",func=function() AT2_Print("not yet implemented, testing","error") end})

		--Time Interval-based sending settings stack
		local timesettingsStack=AT2_UI_CreateStack(AT2_UI2,"timesettingsStack")
		local timesettingsStack_label=AT2_UI_CreateFontString(timesettingsStack,"timesettingsStack_label","EnigmaticSmall","LEFT",4,1)
		timesettingsStack_label:SetText("Időzített mód")
		tinsert(AT2_UI2,AT2_UI_CreateLine(timesettingsStack,timesettingsStack_label:GetStringWidth()+2,nil,1,19,"LEFT"))
		
		--Per-Message-based sending settings stack
		local msgsettingsStack=AT2_UI_CreateStack(AT2_UI2,"msgsettingsStack")
		local msgsettingsStack_label=AT2_UI_CreateFontString(msgsettingsStack,"messageStack_label","EnigmaticSmall","LEFT",4,1)
		msgsettingsStack_label:SetText("Üzenetenkénti mód")
		tinsert(AT2_UI2,AT2_UI_CreateLine(msgsettingsStack,msgsettingsStack_label:GetStringWidth()+2,nil,1,19,"LEFT"))
		

		--the rest
		local resizeHandle=CreateFrame("Button",nil,AT2_UI2)
		resizeHandle:SetWidth(12)
		resizeHandle:SetHeight(16)
		resizeHandle:SetPoint("RIGHT",AT2_UI2,"RIGHT",16,0)
		resizeHandle:SetNormalTexture("Interface\\AddOns\\AutoTalker2\\resizeline")
		resizeHandle:GetNormalTexture():SetAlpha(.5)
		resizeHandle:SetHighlightTexture("Interface\\AddOns\\AutoTalker2\\resizehover")
		local resizebg=resizeHandle:CreateTexture()
		resizebg:SetTexture("Interface\\AddOns\\AutoTalker2\\resizebg")
		resizebg:SetPoint("LEFT",AT2_UI2,"RIGHT")
		resizebg:SetWidth(32)
		resizebg:SetAlpha(.125)
		resizebg:SetHeight(AT2_UI2:GetHeight())

		resizeHandle:SetScript("OnMouseDown",function() AT2_UI2:StartSizing("RIGHT") end)
		resizeHandle:SetScript("OnMouseUp",function() AT2_UI2:StopMovingOrSizing() end)
		resizeHandle:SetScript("OnEnter",function() UIFrameFadeIn(resizebg, .25, resizebg:GetAlpha(), .5) end)
		resizeHandle:SetScript("OnLeave",function() UIFrameFadeIn(resizebg, 1, resizebg:GetAlpha(), .125) end)

		AT2_UI2_AddUIEvent(AT2_UI2,"Unfocus",function() AT2_UI2["!messageStack"]["!AT2_UI_MessageEditBox"]:ClearFocus() end) -- this is kinda a special case, manually fired event; also needs rewrite to parse through all the frames to unfocus
		WorldFrame:HookScript("OnMouseDown",function() AT2_UI2_FireUIEvents(AT2_UI2,"Unfocus") end)

		AT2_UI_SetupTooltipStrings()

		AT2_UI_InitDone=true
		AT2_Print("Done","debug","AT2_UI_Init")
	else
		AT2_Print("called but already done","debug","AT2_UI_Init")
	end
end


function AT2_ShowUI()
	if not(AT2_UI_InitDone) then AT2_UI_Init() end
	if not(AT2_UI2:IsVisible()) then
		if not(AT2_Save["firstrundone"]) then 
			AT2_Print("Running FirstRunAnimation","debug","AT2_ShowUI")
			local bf=CreateFrame("Frame")
			local bf2=CreateFrame("Frame",nil,bf)
			bf:SetWidth(AT2_UI2:GetWidth()+64)
			bf:SetHeight(AT2_UI2:GetHeight()+64)
			bf2:SetWidth(GetScreenWidth())
			bf2:SetHeight(GetScreenHeight())
			bf:SetBackdrop( {bgFile="Interface\\BUTTONS\\WHITE8X8",insets={left=32,top=32,bottom=32,right=32} ,tile=false,edgeFile=[[Interface\Addons\SharedMediaAdditionalFonts\Borders\glow.tga]],edgeSize=32 })
			bf2:SetBackdrop({bgFile="Interface\\BUTTONS\\WHITE8X8",tile=false,edgeFile=[[Interface\Addons\SharedMediaAdditionalFonts\Borders\glow.tga]],edgeSize=1 })
			bf:SetBackdropColor(1,1,1,1)
			bf2:SetBackdropColor(1,1,1,.5)
			bf:SetBackdropBorderColor(1,1,1,.5)
			bf:SetPoint("CENTER",AT2_UI2,"CENTER")
			bf:SetFrameStrata("HIGH")
			bf:SetFrameLevel(50)
			bf:Raise()
			bf:Show()
			bf2:Show()
			bf:SetAlpha(0)
			local z ={ } 
			local g={ }
			g.mode="OUT"
			g.timeToFade=1
			z.mode="IN" 
			z.timeToFade=.25 
			z.finishedFunc=function() 
				AT2_Print("Bloomglow fade finished, showing main UI","debug","AT2_ShowUI")
				UIFrameFade(bf,g)
				UIFrameFadeIn(AT2_UI2,1,0,1)
				AT2_Save["firstrundone"]=true
			end 
			UIFrameFade(bf,z)
		else
			AT2_UI2:Show()
		end
		AT2_UI2_FireUIEvents(AT2_UI2,"Show")
	else
		AT2_Print("Called but already visible","debug","AT2_ShowUI")
	end
end


function AT2_UI2_AddUIEvent(frame,event,func)
	AT2_UI_UIEvents = AT2_UI_UIEvents or {}
	AT2_UI_UIEvents[frame] = AT2_UI_UIEvents[frame] or {}
	AT2_UI_UIEvents[frame][event] = AT2_UI_UIEvents[frame][event] or {}
	tinsert(AT2_UI_UIEvents[frame][event],func)
	if not(AT2_UI_UIEvents[frame][event]) then
		if strsub(event,1,2)=="On" then
			frame:SetScript(event,function() AT2_UI2_FireUIEvents(frame,event) end)
		else
			frame:RegisterEvent(event)
			frame:SetScript("OnEvent",function() AT2_UI2_FireUIEvents(frame,event) end)
		end
	end
end


function AT2_UI2_FireUIEvents(frame, event)
	AT2_Print("•goldFr:•xc "..tostring(frame).." •goldE:•xc"..event.." •goldFu:•xc"..tostring(func),"debug","FireUIEvents")
	if (AT2_UI_UIEvents and AT2_UI_UIEvents[frame] and AT2_UI_UIEvents[frame][event]) then
		for event,func in pairs(AT2_UI_UIEvents[frame][event]) do
			AT2_Print("Found func: •goldFr: •xc"..tostring(frame).." •goldE:•xc"..event.." •goldFu:•xc"..tostring(func),"debug","FireUIEvents")
			func()
		end
	end
end


function AT2_UI_SetupTooltipStrings()
AT2_TooltipStrings2 = {} -- ToDo: remove '2'
AT2_TooltipStrings2["AT2_UI_StartStop_Activated"] = {"Leállítja az automatikus küldést"}
AT2_TooltipStrings2["!AT2_UI_StartStop"] = {"Elindítja az automatikus küldést","Addig nem indíthatod el az automatikus küldést, amíg nem választottál ki egy csatornát, egy küldési módot, és annak a tulajdonságait!"}
AT2_TooltipStrings2["AT2_UI_TimedMode_Auto"]={"A megadott csatornán 1 percig figyeli az üzenetek számát, és az alapján állít be egy időt.","Addig nem állíthatsz be időzített küldésre automatikusan időt, amíg nem választod ki ezt a módot, és nincs megadva egy csatorna!"}
AT2_TooltipStrings2["AT2_UI_MessageMode_Auto"]={"A megadott csatornán 1 percig figyeli az üzenetek számát, és az alapján állít be egy üzenetsűrűséget.","Addig nem állíthatsz be üzenetenkénti küldésre automatikusan üzenetsűrűséget, amíg nem választod ki ezt a módot, és nincs megadva egy csatorna!"}
AT2_TooltipStrings2["AT2_UI_PluginsButton"]={"Különbözö pluginokat kapcsolhatsz ki és be\nPl.: Automatikus küldés leállítása egy bizonyos tartalmú privát üzenetkor, stb."}
AT2_TooltipStrings2["AT2_UI_SavedMessages_List"]={"Megnyitja a mentett üzenetek listáját.","Nincs még egy mentett üzenet sem."}
AT2_TooltipStrings2["AT2_UI_SavedMessages_Delete"]={"Törli a jelenleg kiválasztott mentett üzenetet.","Nincs kiválasztva mentett üzenet."}
AT2_TooltipStrings2["AT2_UI_SavedMessages_Insert"]={"Beilleszti a fő szövegdobozba a jelenleg kiválasztott mentett üzenetet.&Nincs kiválasztva mentett üzenet."}
-- 2B Continued
end

function AT2_UI_OnResize()
	for name,frame in pairs(AT2_UI2) do
		if strsub(name,1,1)=="!" and frame.autoSize and (tContains(AT2_UI2.stacks,frame) or strsub(name,1,5)=="!Line")  then
			frame:SetWidth(AT2_UI2:GetWidth())
			for sname,sframe in pairs(frame) do
				if (strsub(sname,1,1)=="!" and sframe.specialAutoSize) then
					sframe:SetWidth(sframe.specialAutoSize())
				elseif (strsub(sname,1,5)=="!Line" and sframe:GetHeight()<2) then
					sframe:SetWidth(frame:GetWidth())
				end
			end
		end
	end
end

function AT2_UI_CreateFrames(info)
	if (type(info)=="table") then
		if (type(info[1])~="table") then
			for k,v in pairs(info) do
					if (type(v)=="table") then
						if (v.controlType=="panel") then
							if (v.prefunc) then v.prefunc() end
							local panel=CreateFrame("Frame",nil,WorldFrame)
							if (v.prefuncwithobject) then v.prefuncwithobject(panel) end

							panel.frames=panel.frames or {}
							panel.fname=v.fname
							panel:SetToplevel(v.Toplevel)
							if (v.frameStrata) then panel:SetFrameStrata(v.frameStrata) end
							if (v.enableMouse) then panel:EnableMouse(v.enableMouse) end
							panel:SetMovable(v.movable)
							panel:SetResizable(v.resizeable)
							panel:SetWidth(v.width)
							if (v.minResize) then panel:SetMinResize(v.minResize.width,v.minResize.height)
							panel:SetHeight(v.height)
							panel:SetBackdrop({bgFile="Interface\\BUTTONS\\WHITE8X8",tile=false,edgeFile="Interface\\BUTTONS\\WHITE8X8",edgeSize=1})
							panel:SetBackdropColor(0, 0, 0, .65)
							panel:SetPoint(v.point)
							panel:Hide()
							if (v.postfunc) then v.postfunc(panel) end

						elseif (v.controlType=="stack") then 
							AT2_UI_CreateStack(v)
						elseif (v.controlType=="button") then
							AT2_UI_CreateButton(v)
						elseif (v.controlType=="fontstring") then
							AT2_UI_CreateFontString(v)
						elseif (v.controlType=="radiobutton") then
							AT2_UI_CreateRadioButton(v)
						end
					end
				end
			end
		else
			AT2_UI_CreateFrames({info})
		end
		return true
	else 
		return false
	end
end

function AT2_UI_CreateStack(pframe,name)
	local _stack=CreateFrame("Frame",nil,pframe)
	_stack.autoSize=true
	_stack.fname="!"..name
	_stack.frames=_stack.frames or {} -- kinda legacy but needed for resizing, maybe needed to rework
	pframe.frames=pframe.frames or {}
	_stack:SetWidth(pframe:GetWidth())
	_stack:SetHeight(18)
	pframe.stacks=pframe.stacks or {}
	tinsert(pframe.stacks,_stack)
	pframe:SetHeight(pframe:GetHeight()+19)
	--_stack:SetPoint("BOTTOM",0,(#pframe.stacks*19)-19)
	local posYtoSet=0
	if (pframe.stacks[#pframe.stacks-1]) then posYtoSet=({pframe.stacks[#pframe.stacks-1]:GetPoint()})[5]+pframe.stacks[#pframe.stacks-1]:GetHeight()+1 end
	_stack:SetPoint("BOTTOM",0,posYtoSet)
	tinsert(_stack.frames,AT2_UI_CreateLine(_stack,nil,18,_stack:GetWidth(),1,"BOTTOM"))
	pframe[_stack.fname]=_stack
	return _stack
end

function AT2_UI_DestroyStack(pframe,i) --todo: test, not tested at all, possibly unfinished
	if not(i) then local i=pframe.stacks[#pframe.stacks] end -- ^ as of 140817 still not tested...
	local _stack=pframe.stacks[i]
	_stack:ClearAllPoints()
	_stack:SetParent(nil)
	_stack:Hide()
	tremovebyval(pframe.stacks,_stack)
	pframe[_stack.fname]=nil
	
end



function AT2_UI_CreateButton(info)
	-- info table original flags: parent,name,text,point,posX,posY,width,height,relativePoint
	local button=CreateFrame("Button",nil,info.parent)
	local label=AT2_UI_CreateFontString(button,info.name.."_label","Enigmatic","CENTER")
	label:SetText(info.text)
	button.fname="!"..info.name
	button.frames={}
	button.type="button"
	button.Enabled=true
	button:SetPoint(info.relativePoint,info.parent,info.point,(info.posX or 0),(info.posY or 0))
	button:SetHeight(info.height or 17)
	button:SetWidth(info.width or label:GetStringWidth()+8)
	label:SetPoint("CENTER")
	button:SetNormalTexture("Interface\\BUTTONS\\WHITE8X8")
	button:GetNormalTexture():SetTexture(0,0,.5,.5)
	--normalTexture:SetTexture(0,0,.5,.5)
	--disabledTexture:SetTexture(.5,0,0,.5)
	button:SetHighlightTexture("Interface\\BUTTONS\\WHITE8X8")
	button:GetHighlightTexture():SetTexture(1,1,1,.125)
	button:Show()
	
	function button:Disable() button:SetNormalTexture("Interface\\BUTTONS\\WHITE8X8") button:GetNormalTexture():SetTexture(.5,0,0,.5) button.Enabled=false end
	function button:Enable() button:SetNormalTexture("Interface\\BUTTONS\\WHITE8X8") button:GetNormalTexture():SetTexture(0,0,.5,.5) button.Enabled=true end

	button:SetScript("OnClick",function(button, ...) AT2_UI2_FireUIEvents(button, "OnClick", ...) end) 
	button:SetScript("OnEnter",function() AT2_ShowTooltip2(button) end)
	button:SetScript("OnLeave",function() AT2_ShowTooltip2() end)
	tinsert(info.parent.frames,button)
	info.parent[button.fname]=button
	return button
end

function AT2_UI_CreateRadioButton(info)
	-- info table original flags: parent,name,text,point,posX,posY,width,height,relativePoint
	local button=CreateFrame("Button",nil,info.parent)
	local label=AT2_UI_CreateFontString(button,info.name.."_label","Enigmatic","LEFT")
	label:SetText(info.text)
	button.fname="!"..info.name
	button.frames={}
	button.type="radioButton"
	button.Enabled=true
	button:SetPoint(info.relativePoint,info.parent,info.point,(info.posX or 0),(info.posY or 0))
	button:SetHeight(info.height or 17)
	--button:SetWidth(info.width or label:GetStringWidth()+8+button:GetHeight())
	button:SetWidth(info.width or button:GetHeight())
	--label:SetWidth(button:GetWidth())
	--label:SetPoint("LEFT")
	--button:SetNormalTexture("Interface\\BUTTONS\\WHITE8X8")
	--button:GetNormalTexture():SetTexture(0,0,.5,.5)
	--normalTexture:SetTexture(0,0,.5,.5)
	--disabledTexture:SetTexture(.5,0,0,.5)
	--button:SetHighlightTexture("Interface\\BUTTONS\\WHITE8X8")
	--button:GetHighlightTexture():SetTexture(1,1,1,.125)
	button.basetex="Interface\\AddOns\\AutoTalker2\\Images\\at2_rb"
	button.bliptex="Interface\\AddOns\\AutoTalker2\\Images\\at2_rb_blip"
	local basetex = button:CreateTexture(button)
	basetex:SetTexture(button.basetex)
	basetex:SetWidth(button:GetHeight())
	basetex:SetHeight(button:GetHeight())
	basetex:SetPoint("LEFT",button,"LEFT")
	label:SetPoint("RIGHT",basetex,"LEFT",4,0)
	local bliptex = button:CreateTexture(button)
	bliptex:SetTexture(button.blip)
	bliptex:SetPoint("CENTER",basetex,"CENTER")
	bliptex:SetWidth(bliptex:GetHeight()*(5/12))
	bliptex:SetHeight(bliptex:GetHeight()*(5/12))
	bliptex:Hide()
	button:Show()
	
	function button:Disable() button:SetNormalTexture("Interface\\BUTTONS\\WHITE8X8") button:GetNormalTexture():SetTexture(.5,0,0,.5) button.Enabled=false end
	function button:Enable() button:SetNormalTexture("Interface\\BUTTONS\\WHITE8X8") button:GetNormalTexture():SetTexture(0,0,.5,.5) button.Enabled=true end

	button:SetScript("OnClick",function(button, ...) AT2_UI2_FireUIEvents(button, "OnClick", ...) end) 
	button:SetScript("OnEnter",function() AT2_ShowTooltip2(button) end)
	button:SetScript("OnLeave",function() AT2_ShowTooltip2() end)
	tinsert(info.parent.frames,button)
	info.parent[button.fname]=button
	return button
	--[[
	local rbutton=CreateFrame("Button",nil,info.parent)
	local label=AT2_UI_CreateFontString(rbutton,info.name.."_label","Enigmatic","CENTER")
	label:SetText(info.text)
	rbutton.fname="!"..info.name
	rbutton.frames={}
	rbutton.type="radioButton"
	rbutton.Enabled=true
	rbutton.func=info.func
	rbutton:SetPoint(info.relativePoint,info.parent,info.point,(info.posX or 0),(info.posY or 0))
	rbutton:SetWidth(info.width or label:GetStringWidth()+8)
	rbutton:SetHeight(info.height or 12)
	rbutton.basetex="Interface\\AddOns\\AutoTalker2\\Images\\at2_rb"
	rbutton.bliptex="Interface\\AddOns\\AutoTalker2\\Images\\at2_rb_blip"
	local basetex = rbutton:CreateTexture(rbutton)
	basetex:SetTexture(rbutton.basetex)
	basetex:SetWidth(rbutton:GetHeight())
	basetex:SetHeight(rbutton:GetHeight())
	basetex:SetPoint("LEFT",rbutton,"LEFT")
	label:SetPoint("RIGHT",basetex,"LEFT",4,0)
	local bliptex = rbutton:CreateTexture(rbutton)
	bliptex:SetTexture(rbutton.blip)
	bliptex:SetPoint("CENTER",basetex,"CENTER")
	bliptex:SetWidth(bliptex:GetHeight()*(5/12))
	bliptex:SetHeight(bliptex:GetHeight()*(5/12))
	bliptex:Hide()

	function rbutton:Disable() basetex:SetDesaturated(true) bliptex:SetDesaturated(true) rbutton.Enabled=false end
	function rbutton:Enable()  basetex:SetDesaturated(false) bliptex:SetDesaturated(false) rbutton.Enabled=true end
	AT2_UI2_AddUIEvent(rbutton,"OnEnter",function() if (rbutton.Enabled) then bliptex:Show() bliptex:SetAlpha(.5) end end)
	AT2_UI2_AddUIEvent(rbutton,"OnLeave",function() if (rbutton.Enabled) then bliptex:Hide() bliptex:SetAlpha(1) end end)
	AT2_UI2_AddUIEvent(rbutton,"OnMouseDown",function() 
		if (rbutton.Enabled) then 
			for k,v in rbutton:GetParent().frames do 
				if k.type=="radioButton" then 
					bliptex:Hide() bliptex:SetAlpha(1) 
				end 
			end
			rbutton.func() 
		end
	end)
	tinsert(info.parent.frames,rbutton)
	info.parent[rbutton.fname]=rbutton
	return rbutton
	]]

end


function AT2_UI_CreateEditBox(info)
	-- todo: add numeric flag, with up/down buttons (like numericUpDown in windows, but) with mouseover
	--info table original flags: parent,name,point,posX,posY,width,height,relativePoint
	local editbox=CreateFrame("EditBox",nil,info.parent)
	editbox.fname="!"..info.name
	editbox.frames={}
	editbox.Enabled=true
	editbox:SetAutoFocus(false)
	editbox:SetNumeric(info.numeric or false)
	--if (info.numeric) then --todo
	editbox:SetHeight(info.height or 18)
	editbox:SetWidth(info.width)
	editbox:SetTextInsets(4,0,0,0)
	if (info.hint) then
		local hint=AT2_UI_CreateFontString(editbox,strsub(editbox.fname,2).."_Hint","Enigmatic","LEFT",4,0)
		hint:SetText(AT2_StringFormat("•gray"..info.hint.."•xc"))
		AT2_UI2_AddUIEvent(editbox,"OnEditFocusGained",function() hint:Hide() end)
		AT2_UI2_AddUIEvent(editbox,"OnEditFocusLost",function() if (editbox:GetText():len()==0) then hint:Show() end end)
	end
	editbox:EnableKeyboard(true)
	editbox:SetPoint(info.relativePoint,info.parent,info.point,(info.posX or 0),(info.posY or 0))
	editbox:SetFont(AT2_UI2.Fonts["Enigmatic"]:GetFont())
	tinsert(editbox.frames,AT2_UI_CreateLine(editbox,0,0,1,editbox:GetHeight(),"LEFT"))
	tinsert(editbox.frames,AT2_UI_CreateLine(editbox,0,0,1,editbox:GetHeight(),"RIGHT"))
	editbox:SetScript("OnEnter",function() AT2_ShowTooltip2(editbox) end)
	editbox:SetScript("OnLeave",function() AT2_ShowTooltip2() end)
	editbox:SetScript("OnEditFocusGained",function(editbox, ...) AT2_UI2_FireUIEvents(editbox, "OnEditFocusGained", ...) end)
	editbox:SetScript("OnEditFocusLost",function(editbox, ...) AT2_UI2_FireUIEvents(editbox, "OnEditFocusLost", ...) end)
	editbox:SetScript("OnEscapePressed",function(editbox, ...) editbox:ClearFocus() end)
	editbox:Show()
	info.parent[editbox.fname]=editbox
	return editbox
end


function AT2_UI_CreateFontString(frame,name,font,point,posX,posY) -- note: added /name/ as second parameter!!
	local fs=frame:CreateFontString()
	fs:SetFont(AT2_UI2.Fonts[font]:GetFont())
	fs:SetPoint(point,frame,point,(posX or 0),(posY or 0))
	fs.fname="!"..name
	frame[fs.fname]=fs
	return fs
end

function AT2_UI_CreateLine(frame,posX,posY,width,height,relativePoint)
	local line=frame:CreateTexture()
	line.autoSize=true
	line:SetTexture("Interface\\BUTTONS\\WHITE8X8")
	AT2_UI2.LinesCounter=AT2_UI2.LinesCounter+1
	line.fname="!Line"..AT2_UI2.LinesCounter
	--ToDo: implement set color by black/white theme
	--line:SetTexture(0,0,0,1)
	relativePoint=relativePoint or "BOTTOMLEFT"
	posX=posX or 0
	posY=posY or 0
	line:SetPoint(relativePoint,posX,posY)
	line:SetWidth(width)
	line:SetHeight(height)
	frame[line.fname]=line
	-- ToDo: make version of parentframe[!thisframename]=thisframe for white separator lines; will be a method/way to control color
	return line
end


local function AT2_GetChildrenFrames(frame)
	local t = {}
   	for k,v in pairs(frame) do
   		if (strsub(k,1,1)=="!") then
	    	tinsert(t,v)
    	end
   	end
   	return t
end

local function AT2_GetFrameEvents(frame)
	local t = {}
	if (AT2_UI_UIEvents[frame]) then
		for k,v in pairs(AT2_UI_UIEvents[frame]) do
			tinsert(t,k)
		end
	end
	return t
end


function AT2_ShowTooltip2(name) -- ToDo: set all references to their non-2 version
	if name and name.fname then -- yo dawg
		local hasTip
		AT2_Print("•goldN:•xc"..tostring(name).." •goldfN:•xc"..tostring(name.fname),"debug","ShowTooltip2")
		local text=""
		GameTooltip:SetOwner(AT2_UI2,"ANCHOR_CURSOR")
		if AT2_TooltipStrings2[name.fname] then
			hasTip=true
			if not(name.Enabled==false) then
				text=text..AT2_TooltipStrings2[name.fname][1]
			else
				text=text..AT2_TooltipStrings2[name.fname][2]
			end
		end
		if (AT2_Save["debugenabled"]) then 
				if hasTip then text=text.."\n\n" end
				text=text.."•yellowFrame:•xc •cyan"..name.fname.."•xc"
				if (name:GetParent() and (name:GetParent():GetName() or name:GetParent().fname)) then text=text.."\n•yellowParent: •cyan"..(name:GetParent():GetName() or name:GetParent().fname).."•xc" end
				local childrenFrames=AT2_GetChildrenFrames(name)
				if (#childrenFrames>0) then text=text.."\n•cyan"..AT2_Lang_Plural(#childrenFrames,"frame","frames","•xc •graytop-level•xc •yellowchild").."•xc" 
					for i=1,#childrenFrames do
						text=text.."\n    •yellow"..childrenFrames[i]:GetObjectType().."•xc •cyan"..childrenFrames[i].fname.."•xc"
					end
				end
				local frameEvents=AT2_GetFrameEvents(name)
				if (#frameEvents>0) then text=text.."\n•cyan"..AT2_Lang_Plural(#frameEvents,"•yellowevent","•yellowevents").."•xc"
					for i=1,#frameEvents do
						text=text.."\n    •yellow"..frameEvents[i].."•xc •graywith "..AT2_Lang_Plural(#AT2_UI_UIEvents[name][frameEvents[i]],"function","functions").."•xc"
					end
				end
		end
		if not(text=="") then GameTooltip:SetText(AT2_StringFormat(text)) GameTooltip:Show() end
	else
		GameTooltip:Hide()
	end
end 

-- pre-refactor functions beyond this point


function AT2_UIButtonAutoSize(name)
	AT2_Print("•goldname:•xc "..name:GetName().."; •goldstringwidth:•xc "..getglobal(name:GetName().."Text"):GetStringWidth().."+5","debug","UIButtonAutoSize")
	name:SetWidth(getglobal(name:GetName().."Text"):GetStringWidth()+5)
end

function AT2_UIHider() -- Ez azért kell, hogy eltűnjön az UI, mikor az Alt+Z -t lenyomod. Az pedig azért kellett, hogy külön mérete legyen az ablaknak a wow UIjától, ergo nincsenek különböző méretű vonalak.
   if not(UIParent:IsVisible()) then
      AT2_UI:Hide()
   end
end

function AT2_WFHookHandler() -- wf=worldframe
local v = AT2_UI:IsVisible()
   AT2_Print("UIVisible? "..tostring(v).."!","debug","AT2_WFHookHandler")
   if (v) then
		AT2_UI_CustChanEditBox:ClearFocus()
		AT2_UI_EditBox:ClearFocus()
		AT2_UI_TimedMode_Seconds:ClearFocus()
		AT2_UI_TimedMode_Minutes:ClearFocus()
		AT2_UI_MessageMode_MessageNum:ClearFocus()
		AT2_UI_SavedMessages_EditBox:ClearFocus()

   end
end

function AT2_UI_EmptyEditBox(name, msg,func)
if func == nil then func = "nil" end
local n = name:IsNumeric()
local t=name:GetText():gsub("\124cff9d9d9d",""):gsub("\124r","")
AT2_Print("N:"..name:GetName().." T:"..t.." M:"..msg.." F:"..func.." Num: "..tostring(n),"debug","EmptyEditBox")
	if (func == "focus" and (tonumber(t) == msg or t == msg)) then
		if n then name:SetTextColor(1,0.85,0) end
		name:SetText("")
		
	elseif (func == "focuslost" and name:GetText() == "") then
		if n then name:SetNumber(msg) name:SetTextColor(0.5,0.5,0.5) else
			name:SetText("\124cff9d9d9d"..msg.."\124r")
		end
	end
end

function AT2_EnableEditBox(name)
AT2_Print("N: AT2CW"..name:GetName().."AT2CE","debug","EnableEditBox")
name:EnableKeyboard(1)
name:EnableMouse(1)
name:SetTextColor(1,0.85,0)
end
function AT2_DisableEditBox(name)
AT2_Print("N: AT2CW"..name:GetName().."AT2CE","debug","DisableEditBox")
name:EnableKeyboard(0)
name:EnableMouse(0)
name:SetTextColor(0.5,0.5,0.5)
end


function AT2_ShowTooltip(name)
	if name then
		if AT2_TooltipStrings[name:GetName()] then
		GameTooltip:SetOwner(AT2_UI,"ANCHOR_CURSOR")
AT2_temp_dbtnchk=nil
		if select(1, name:GetNormalTexture():GetVertexColor()) > 0.1 then AT2_temp_dbtnchk = 1 end
		if AT2_temp_dbtnchk then
			GameTooltip:SetText(select(2, strsplit("&", AT2_TooltipStrings[name:GetName()])),1,1,1,1,1)
		else
			-- ez a kód itt ronda és kurvára nem így kéne megoldani; így sikerült (de nagyon)
			if (name:GetName() == "AT2_UI_StartStop" and AT2_Activated==1) then
				GameTooltip:SetText(select(1, strsplit("&", AT2_TooltipStrings[name:GetName().."_Activated"])),1,1,1,1,1)
			else
				GameTooltip:SetText(select(1, strsplit("&", AT2_TooltipStrings[name:GetName()])),1,1,1,1,1)
			end
		end
			GameTooltip:Show()
		else
			GameTooltip:Hide()
		end
	else
		GameTooltip:Hide()
	end
end 

function AT2_DisableButton(name)
name:SetNormalFontObject(Enigmatic_D)
name:GetNormalTexture():SetVertexColor(0.5,0,0,0.5)
end

function AT2_EnableButton(name)
name:SetNormalFontObject(Enigmatic)
name:GetNormalTexture():SetVertexColor(0,0,0.5,0.5)
end

function AT2_UIEventHandler(name,event) -- ezt mindenképp kategorizálni kéne vagy szétbontani, mert most így átláthatatlan
	AT2_MessageEditBoxHelp = "Ide írd az üzenetet"
	AT2_SavedMessageEditBoxHelp="Ide írd az üzenetet miután választottál vagy készítettél új mentést"
	AT2_ChannelEditBoxHelp = "Csatorna neve"
	local e=event;local c="click";local efg="editfocusgained";local efl="editfocuslost";local tc="textchanged";local md="mousedown";local mu="mouseup";local me="mouseenter";local ml="mouseleave";local r="resize";local s="show";u="update"
	local nname=name:GetName()
	local currentframeisdisabled = false
	
	AT2_UI_SavedMessages_Eventhandler(name,event)
	
	if e==c and not(name.alwaysenabled) then  -- if e==c and (name.alwaysenabled) then
		AT2_Print("Click event & frame can be disabled","debug","UIEventHandler")
		if select(1, name:GetNormalTexture():GetVertexColor()) > 0.1 and select(3, name:GetNormalTexture():GetVertexColor()) < 0.7 then
			AT2_Print("Frame is AT2CRdisabledAT2CE","debug","UIEventHandler")
			currentframeisdisabled=true
		end
	end
	if currentframeisdisabled==true then
		AT2_Print(select(2, strsplit("&", AT2_TooltipStrings[name:GetName()])),"error")
	else
		--AT2_Print("Frame is AT2CGnot disabledAT2CE","debug","UIEventHandler")
		if nname == "AT2_UI_Close" and e==c then
			AT2_UI:Hide()
		elseif nname == "AT2_UI_EditBox" and e==tc then
			AT2_UI_CharLeft:SetText("Üzenet ("..strsub(AT2_RedYellowGreenNum(AT2_UI_EditBox:GetNumLetters(),AT2_UI_EditBox),1).."/250)")
			AT2_UI_EditBox:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT",AT2_UI_CharLeft:GetWidth()+9,1)
			AT2_UI_EditBox:SetWidth(AT2_UI:GetWidth()-(AT2_UI_CharLeft:GetWidth()+AT2_UI_StartStop:GetWidth()+14))
			AT2_message=AT2_UI_EditBox:GetText()
			AT2_Print("MSGChanged: "..AT2_message,"debug","AT2_UIEventHandler, "..nname..", "..e)
		elseif nname=="AT2_UI_EditBox" and e==efg then
			AT2_UI_EmptyEditBox(name,AT2_MessageEditBoxHelp, "focus")
		elseif nname=="AT2_UI_EditBox" and e==efl then
			AT2_UI_EmptyEditBox(name,AT2_MessageEditBoxHelp, "focuslost")
		elseif nname=="AT2_UI_SavedMessages_EditBox" and e==efg then
			AT2_UI_EmptyEditBox(name,AT2_MessageEditBoxHelp, "focus")
		elseif nname=="AT2_UI_SavedMessages_EditBox" and e==efl then
			AT2_UI_EmptyEditBox(name,AT2_MessageEditBoxHelp, "focuslost")
		elseif nname=="AT2_UI_SavedMessages_EditBox" and e==tc then
			AT2_UI_SavedMessages_CharLeft:SetText(strsub(AT2_RedYellowGreenNum(AT2_UI_SavedMessages_EditBox:GetNumLetters(),AT2_UI_SavedMessages_EditBox),1).."/250 karakter")
			if (AT2_SelectedSavedMessage==nil) then
				AT2_UI_EmptyEditBox(name,AT2_SavedMessageEditBoxHelp,"focuslost")
			else
				if AT2_UI_SavedMessages_EditBox:GetText()~="" then
					AT2_WriteSavedMessage("msg",AT2_SelectedSavedMessage,AT2_UI_SavedMessages_EditBox:GetText())
				end
			end
		elseif nname=="AT2_UI_TimedMode_Minutes" and e==efg then
			AT2_UI_EmptyEditBox(name,2, "focus")
		elseif nname=="AT2_UI_TimedMode_Minutes" and e==efl then
			AT2_UI_EmptyEditBox(name,2, "focuslost")
		elseif nname=="AT2_UI_TimedMode_Minutes" and e==tc then
		AT2_SendInterval = AT2_UI_TimedMode_Minutes:GetNumber()*60+AT2_UI_TimedMode_Seconds:GetNumber()
		elseif nname=="AT2_UI_TimedMode_Seconds" and e==efg then
			AT2_UI_EmptyEditBox(name,30, "focus")
		elseif nname=="AT2_UI_TimedMode_Seconds" and e==efl then
			AT2_UI_EmptyEditBox(name,30, "focuslost")
		elseif nname=="AT2_UI_TimedMode_Seconds" and e==tc then
			AT2_SendInterval = AT2_UI_TimedMode_Minutes:GetNumber()*60+AT2_UI_TimedMode_Seconds:GetNumber()
			AT2_UI_ParseSendMode()
		elseif nname=="AT2_UI_MessageMode_MessageNum" and e==efg then
			AT2_UI_EmptyEditBox(name,25, "focus")
		elseif nname=="AT2_UI_MessageMode_MessageNum" and e==efl then
			AT2_UI_EmptyEditBox(name,25, "focuslost")
		elseif nname=="AT2_UI_MessageMode_MessageNum" and e==tc then
			AT2_SendMMInterval=AT2_UI_MessageMode_MessageNum:GetNumber()
			AT2_UI_ParseSendMode()
		elseif nname=="AT2_UI_CustChanEditBox" and e==efg then
			name:SetMaxBytes(16)
			AT2_UI_EmptyEditBox(name,AT2_ChannelEditBoxHelp, "focus")
		elseif nname=="AT2_UI_CustChanEditBox" and e==efl then
			name:SetMaxBytes(64)
			AT2_UI_EmptyEditBox(name,AT2_ChannelEditBoxHelp, "focuslost")
		elseif nname=="AT2_UI_CustChanEditBox" and e==tc then
			AT2_ExternalChannel = AT2_UI_CustChanEditBox:GetText()
			AT2_UI_ParseSendMode()
		elseif strfind(nname, "AT2_UI_MCB") and e==c then
			AT2_UI_HandleModeCB(name)
			AT2_Print("M-checkbox","debug","UIEventHandler")
		elseif strfind(nname,"AT2_UI_CCB") and e==c then
			AT2_UI_HandleChannelCB(name)
		elseif nname=="AT2_UI_TimedMode_Auto" and e==c then
			AT2_UI_SetStatusBar("!clear")
			AT2_MeasuringMessages=1
			AT2_MessagesInAMinute=0
			AT2_MeasureMessages(time())
		elseif nname=="AT2_UI_MessageMode_Auto" and e==c then
			AT2_UI_SetStatusBar("!clear")
			AT2_MeasuringMessages=1
			AT2_MessagesInAMinute=0
			AT2_MeasureMessages(time())
		elseif nname=="AT2_UI_SavedMessages" and e==s then
			if tcount(AT2_Save["Messages"]) == 0 then
				AT2_DisableButton(AT2_UI_SavedMessages_List)
			else
				AT2_EnableButton(AT2_UI_SavedMessages_List)
			end
			if not(AT2_SelectedSavedMessage==0 or AT2_SelectedSavedMessage==nil) then 
				AT2_EnableButton(AT2_UI_SavedMessages_Delete)
				AT2_EnableButton(AT2_UI_SavedMessages_Insert)
			else
				AT2_DisableButton(AT2_UI_SavedMessages_Delete)
				AT2_DisableButton(AT2_UI_SavedMessages_Insert)
				
			end
		elseif nname=="AT2_UI_SavedMessages_Delete" and e==c then
			tremove(AT2_Save["Messages"],AT2_SelectedSavedMessage)
			AT2_SelectedSavedMessage=tostring(tcount(AT2_Save["Messages"]))
			if not(AT2_SelectedSavedMessage==0  or AT2_SelectedSavedMessage==nil) then 
				AT2_UI_SavedMessages_EditBox:SetText(AT2_ReadSavedMessage("msg",AT2_SelectedSavedMessage));
				AT2_UI_SavedMessages_Name:SetText(AT2_ReadSavedMessage("name",AT2_SelectedSavedMessage));
				if (AT2_ReadSavedMessage("q",AT2_SelectedSavedMessage)=="+") then
					AT2_UI_SavedMessages_isQueued:SetChecked(1)
				elseif (AT2_ReadSavedMessage("q",AT2_SelectedSavedMessage)=="X") then
					AT2_UI_SavedMessages_isQueued:SetChecked(0)
				end
			else
				AT2_DisableButton(AT2_UI_SavedMessages_List)
				AT2_DisableButton(AT2_UI_SavedMessages_Delete)
				AT2_DisableButton(AT2_UI_SavedMessages_Insert)
				AT2_UI_SavedMessages_EditBox:SetText("")
				AT2_UI_SavedMessages_Name:SetText("")
				AT2_UI_SavedMessages_isQueued:SetChecked(0)
			end
		elseif nname=="AT2_UI_SavedMessages_List" and e==c then
			local menu = { }
			for i=1,tcount(AT2_Save["Messages"]) do
			local AT2temp_isSorban=""
			if (AT2_ReadSavedMessage("q",i)=="+") then AT2temp_isSorban="[Sorban] " end
			AT2_Print("i="..i..", AT2_ReadSavedMessage(\"name\",i): "..tostring(AT2_ReadSavedMessage("name",i)),"debug","UI_EventHandler, SavedMessages_List button click")
			tinsert(menu,{text=AT2temp_isSorban..AT2_ReadSavedMessage("name",i),func=function() 
			AT2_SelectedSavedMessage=tostring(i)
			AT2_EnableButton(AT2_UI_SavedMessages_Delete)
			AT2_EnableButton(AT2_UI_SavedMessages_Insert)
			AT2_UI_SavedMessages_EditBox:SetText(AT2_ReadSavedMessage("msg",AT2_SelectedSavedMessage));
			AT2_UI_SavedMessages_Name:SetText(AT2_ReadSavedMessage("name",AT2_SelectedSavedMessage));
			if (AT2_ReadSavedMessage("q",AT2_SelectedSavedMessage)=="+") then
				AT2_UI_SavedMessages_isQueued:SetChecked(1)
			elseif (AT2_ReadSavedMessage("q",AT2_SelectedSavedMessage)=="X") then
				AT2_UI_SavedMessages_isQueued:SetChecked(0)
			end
			if (IsShiftKeyDown()) then AT2_UI_SavedMessages_Insert:Click() AT2_UI_SavedMessages_Close:Click() end
			end, tooltipTitle=AT2_ReadSavedMessage("msg",i),tooltipOnButton=true})
			end
			-- Note that this frame must be named for the dropdowns to work.
			local menuFrame = CreateFrame("Frame", "AT2_UI_SavedMessages_dropDown", UIParent, "UIDropDownMenuTemplate")
			
			-- Make the menu appear at the cursor: 
			EasyMenu(menu, menuFrame, "cursor", 0 , 0, "MENU");
			-- Or make the menu appear at the frame:
		--	EasyMenu(menu, menuFrame, menuFrame, 0 , 0, "MENU");
		elseif nname=="AT2_UI_SavedMessages_isQueued" and e==c then
			if (AT2_UI_SavedMessages_isQueued:GetChecked()==1) then
			AT2_WriteSavedMessage("q",AT2_SelectedSavedMessage,true)
			--AT2_Save["Messages"][AT2_SelectedSavedMessage]="+"..AT2_UI_SavedMessages_Name:GetText().."\a"..AT2_UI_SavedMessages_EditBox:GetText()
			elseif (AT2_UI_SavedMessages_isQueued:GetChecked()==nil) then
			AT2_WriteSavedMessage("q",AT2_SelectedSavedMessage,false)
			--AT2_Save["Messages"][AT2_SelectedSavedMessage]="X"..AT2_UI_SavedMessages_Name:GetText().."\a"..AT2_UI_SavedMessages_EditBox:GetText()
			end
		elseif nname=="AT2_UI_StartStop" and e==c then
			AT2_UI_SendButton()
		elseif nname=="AT2_UI_ResizeHandle" and e==md then
			AT2_UI:StartSizing("RIGHT")
		elseif nname=="AT2_UI_ResizeHandle" and e==mu then
			AT2_UI:StopMovingOrSizing()
		elseif nname=="AT2_UI_ResizeHandle" and e==me then
			UIFrameFadeIn(AT2_UI_resizebg, 0.25, AT2_UI_resizebg:GetAlpha(), 0.5)
		elseif nname=="AT2_UI_ResizeHandle" and e==ml then
			UIFrameFadeOut(AT2_UI_resizebg, 0.25, AT2_UI_resizebg:GetAlpha(), 0.125)
		elseif nname=="AT2_UI_ReplacesButton" and e==c then
			AT2_UI_Replaces:Show()
			AT2_UI_ResizeHandler()
		elseif nname=="AT2_UI_SavedMessagesButton" and e==c then
			AT2_UI_SavedMessages:Show()
			AT2_UI_ResizeHandler()
		elseif nname=="AT2_UI_SavedMessages_Insert" and e==c then
			--AT2_UI_EditBox:SetText(select(1, strsplit("\a",AT2_Save["Messages"][AT2_SelectedSavedMessage])))
			AT2_UI_EditBox:SetText(AT2_ReadSavedMessage("msg",AT2_SelectedSavedMessage))
			if (IsShiftKeyDown()) then AT2_UI_SavedMessages_Close:Click() end
		elseif nname=="AT2_UI_SavedMessages_New" and e==c then
			StaticPopup_Show("AT2_NewSavedMessage")
		elseif nname=="AT2_UI" and e==s then
		AT2_Print("UI Show()","debug","AT2_UI, show")
			AT2_UI_AnimateShow()
		--[[elseif nname=="AT2_UI" and e==me then mInsideAT2_UI=true
		elseif nname=="AT2_UI" and e==ml then mInsideAT2_UI=false]]
		elseif nname=="AT2_UI" and e==r then
			AT2_UI_ResizeHandler()		 
		elseif nname=="AT2_UI" and e==u and AT2_UI:IsVisible() then
		mInsideAT2_UI=true
			--local mx,my=GetCursorPosition()
			--local mInsideAT2_UI = (isBetween(mx,select(1, GetAbsolutePosition(AT2_UI)),select(1, GetAbsolutePosition(AT2_UI))+AT2_UI:GetWidth()+28) and (isBetween(my,select(2, GetAbsolutePosition(AT2_UI)),select(2, GetAbsolutePosition(AT2_UI))+AT2_UI:GetHeight())))
			if (mInsideAT2_UI and AT2_UI_resizebg:GetAlpha()<0.24 and not(AT2_UI_MouseWasInside==1)) then --and not(AT2_UI_ResizeHandle:IsVisible())
				UIFrameFadeIn(AT2_UI_resizebg, 0.25, AT2_UI_resizebg:GetAlpha(), 0.125) -- frame, duration, startAlpha, endAlpha
				UIFrameFadeIn(AT2_UI_ResizeHandle, 0.25, AT2_UI_ResizeHandle:GetAlpha(), 1)
				AT2_UI_MouseWasInside=1
				AT2_UI_ResizeHandle:Show()
				AT2_UI_resizebg:Show()
			elseif ((not mInsideAT2_UI) and AT2_UI_ResizeHandle:IsVisible() and AT2_UI_resizebg:GetAlpha()>0 ) then
				if (AT2_UI_MouseWasInside==1) then
				AT2_UI_MouseWasInside=0
					UIFrameFadeOut(AT2_UI_resizebg, 0.5, AT2_UI_resizebg:GetAlpha(), 0)
					UIFrameFadeOut(AT2_UI_ResizeHandle, 0.5, AT2_UI_ResizeHandle:GetAlpha(), 0)
					--AT2_UI_ResizeHandle:Hide()
					--AT2_UI_resizebg:Hide()
				end
			end
		elseif nname=="AT2_UI_ButtonTest" then
			AT2_Print("Yay!")
		else
			if not(tostring(event)=="show") then
				AT2_Print("A(z) \""..nname.."\" objektum \""..tostring(event).."\" funkciója nincs meghatározva!","error")
			end
		end
	end
	
	if (e==tc)then
	AT2_UI_ParseSendMode()
	end
	if (e==c)then
		AT2_UI_ParseSendMode()
	end

		
	if (event == nil) then event = "nil" end
	if not(e==u) then
		AT2_Print("N:AT2CW"..name:GetName().."AT2CE E:AT2CW"..event.."AT2CE","debug","UIEventHandler")
	end
end

function AT2_UI_AnimateShow(lastupdate) -- this one doesn't work at all for some reason. except uiframefadein.
	UIFrameFadeIn(AT2_UI,0.25,0,1)
	AT2_UI_SavedMessages:Hide()
	--[[if (lastupdate==nil) then
	UIFrameFadeIn(AT2_UI,0.25,0,1)
		AT2_UI:SetScale(0.7)
		AT2_Temp_Lastanimation=GetTime()
		AT2_UI_AnimateShow(GetTime())
	else
		if (AT2_UI:GetScale()<0.9) then
			if (AT2_Temp_Lastanimation+0.25 >= lastupdate) then
				AT2_UI:SetScale(AT2_UI:GetScale()+0.1)
				AT2_Temp_Lastanimation = GetTime()
			end
			AT2_UI_AnimateShow(GetTime())
		end
	end]]
end

function AT2_UI_ResizeHandler()
-- main ui
	AT2_UI_EditBox:SetWidth(AT2_UI:GetWidth()-(AT2_UI_CharLeft:GetWidth()+AT2_UI_StartStop:GetWidth()+14))
	AT2_UI_numwhitelines=5
	for i=0,AT2_UI_numwhitelines,1 do
		getglobal("AT2_UI_whiteline"..i):SetWidth(AT2_UI:GetWidth())
	end
	AT2_UI_SettingsButton:SetWidth((AT2_UI:GetWidth()/4)-2)
	AT2_UI_ScriptsButton:SetWidth((AT2_UI:GetWidth()/4)-2)
	AT2_UI_ReplacesButton:SetWidth((AT2_UI:GetWidth()/4)-2)
	AT2_UI_SavedMessagesButton:SetWidth((AT2_UI:GetWidth()/4)-2)
	
-- savedmessages ui
	if tContains(AT2_ModuleList,"SavedPanel") then
		AT2_UI_SavedMessages:SetWidth(AT2_UI:GetWidth()-2)
		AT2_UI_SavedMessages_whiteline0:SetWidth(AT2_UI_SavedMessages:GetWidth())
		AT2_UI_SavedMessages_EditBox:SetWidth(AT2_UI_SavedMessages:GetWidth()-6)
		AT2_UI_SavedMessages_EditBox_whiteline0:SetWidth(AT2_UI_SavedMessages_EditBox:GetWidth()+7)
		AT2_UI_SavedMessages_EditBox_whiteline1:SetWidth(AT2_UI_SavedMessages_EditBox:GetWidth()+7)
		AT2_UI_SavedMessages_EditBox:SetPoint("LEFT",AT2_UI_SavedMessages,"LEFT",3,0)
		AT2_UI_SavedMessages_List:SetWidth(	   ((AT2_UI_SavedMessages:GetWidth()-AT2_UI_SavedMessages_Title:GetWidth()-39.5)/4)-1  )
		AT2_UI_SavedMessages_New:SetWidth(	   ((AT2_UI_SavedMessages:GetWidth()-AT2_UI_SavedMessages_Title:GetWidth()-39.5)/4)-1  )
		AT2_UI_SavedMessages_Delete:SetWidth(  ((AT2_UI_SavedMessages:GetWidth()-AT2_UI_SavedMessages_Title:GetWidth()-39.5)/4)-1  )
		AT2_UI_SavedMessages_Insert:SetWidth(  ((AT2_UI_SavedMessages:GetWidth()-AT2_UI_SavedMessages_Title:GetWidth()-39.5)/4)-1  )
	end
	
	-- replaces ui
	if tContains(AT2_ModuleList,"ReplacesPanel") then
		AT2_UI_Replaces:SetWidth(AT2_UI:GetWidth()-2)
		AT2_UI_Replaces_whiteline0:SetWidth(AT2_UI_Replaces:GetWidth())
		AT2_UI_Replaces_CodeEditBox:SetWidth(AT2_UI_Replaces:GetWidth()-6)
		AT2_UI_Replaces_CodeEditBox_whiteline0:SetWidth(AT2_UI_Replaces_CodeEditBox:GetWidth()+7)
		AT2_UI_Replaces_CodeEditBox_whiteline1:SetWidth(AT2_UI_Replaces_CodeEditBox:GetWidth()+7)
		AT2_UI_Replaces_CodeEditBox:SetPoint("LEFT",AT2_UI_SavedMessages,"LEFT",3,0)
		AT2_UI_Replaces_List:SetWidth(	   ((AT2_UI_Replaces:GetWidth()-AT2_UI_Replaces_Title:GetWidth()-39.5)/4)-1  )
		AT2_UI_Replaces_New:SetWidth(	   ((AT2_UI_Replaces:GetWidth()-AT2_UI_Replaces_Title:GetWidth()-39.5)/4)-1  )
		AT2_UI_Replaces_Delete:SetWidth(   ((AT2_UI_Replaces:GetWidth()-AT2_UI_Replaces_Title:GetWidth()-39.5)/4)-1  )
		AT2_UI_Replaces_Insert:SetWidth(    ((AT2_UI_Replaces:GetWidth()-AT2_UI_Replaces_Title:GetWidth()-39.5)/4)-1  )
	end
end

function AT2_SavedMessagesUpdate()
-- fauxscrollframe helyett uidropdown lesz
-- not yet implemented
end

function AT2_UI_SendButton()
AT2_UI_SetStatusBar("!clear")
if (AT2_LDB_SetText) then AT2_LDB_SetText() end
	if (AT2_Activated==1) then
		AT2_Activated=0
		AT2_UI_StartStop:SetText("Indítás")
		AT2_Print("Leállítva","debug","AT2_UI_SendButton")
	else
		if (AT2_IsValidSetup(AT2_Mode)) then
			if (AT2_Mode=="1") then
				AT2_sendat = 0
				AT2_Activated=1
				AT2_TimedAutoSend(0)
				AT2_UI_StartStop:SetText("Leállítás")
				AT2_Print("Elindítva","debug","AT2_UI_SendButton, TimedMode")
				AT2_UI_SetStatusBar(strsub(date(), 10).." óta fut","r")
			elseif (AT2_Mode=="2") then
				AT2_Activated=1
				AT2_MessageModeAutoSend(0,"")
				AT2_UI_StartStop:SetText("Leállítás")
				AT2_Print("Elindítva", "debug", "AT2_UI_SendButton, MessageMode")
				AT2_UI_SetStatusBar(strsub(date(), 10).." óta fut","r")
			else
				AT2_Print("Érvénytelen küldési mód","error")
			end
		else
			AT2_Print("A feltételek nem felelnek meg a küldéshez!","error")
		end
	end
	AT2_UIButtonAutoSize(AT2_UI_StartStop)
	AT2_UI_EditBox:SetWidth(AT2_UI:GetWidth()-(AT2_UI_CharLeft:GetWidth()+AT2_UI_StartStop:GetWidth()+14))
	if (IsShiftKeyDown()) then AT2_UI_Close:Click() end
end

function AT2_IsValidSetup(AT2_Mode)
	AT2_Print("TimedInt: AT2CW"..AT2_SendInterval.."AT2CE MessageInt: AT2CW"..AT2_SendMMInterval.."AT2CE","debug","IsValidSetup")
	--if (RunScript(dec("QVQyX1NlbmRJbnRlcnZhbCA+IDExOQ==")) or RunScript(dec("QVQyX1NlbmRNTUludGVydmFsID4gMTQ="))) then -- TODO: import b64luamod(Tauriachik)
	if (AT2_Mode=="1") then 
	local mins_secsT = "perc              másodperc (minimum 2 perc)"
		if (AT2_SendInterval > 119) then -- till debug
			AT2_Print("Return true","debug","IsValidSetup")
			return true
		else
			AT2_Print("Return false","debug","IsValidSetup")
			mins_secsT=mins_secsT:gsub("(","(\124cffFF0000"):gsub(")","\124r)")
			return false
		end
		AT2_UI_Mins_Secs:SetText(mins_secsT)
	elseif (AT2_Mode=="2") then
		if (AT2_SendMMInterval > 14) then -- till debug
			AT2_Print("Return true","debug","IsValidSetup")
			AT2_UI_MessageMode_Messages:SetText("üzenetenként (minimum 15 üzenet)")
			return true
		else
			AT2_Print("Return false","debug","IsValidSetup")
			AT2_UI_MessageMode_Messages:SetText("üzenetenként (\124cffFF0000minimum 15 üzenet\124r)")
			return false
		end
	else
		return false
	end
end

function AT2_UI_ParseSendMode()
	if AT2_Mode == "1" then
			
			AT2_DisableEditBox(AT2_UI_MessageMode_MessageNum)
			if (AT2_IsValidSetup(AT2_Mode)) then
			AT2_DisableButton(AT2_UI_MessageMode_Auto)
				if not(AT2_Channel==nil) then
					AT2_EnableButton(AT2_UI_TimedMode_Auto)
					AT2_EnableButton(AT2_UI_StartStop)
				else
					AT2_DisableButton(AT2_UI_TimedMode_Auto)
					AT2_DisableButton(AT2_UI_StartStop)
				end
			else
				AT2_DisableButton(AT2_UI_TimedMode_Auto)
			end
			AT2_EnableEditBox(AT2_UI_TimedMode_Minutes)
			AT2_EnableEditBox(AT2_UI_TimedMode_Seconds)
			elseif AT2_Mode == "2" then
			AT2_DisableEditBox(AT2_UI_TimedMode_Minutes)
			AT2_DisableEditBox(AT2_UI_TimedMode_Seconds)
			
			if (AT2_IsValidSetup(AT2_Mode)) then
				AT2_DisableButton(AT2_UI_TimedMode_Auto)
				if not(AT2_Channel==nil) then
					AT2_EnableButton(AT2_UI_MessageMode_Auto)
					AT2_EnableButton(AT2_UI_StartStop)
				else
					AT2_DisableButton(AT2_UI_MessageMode_Auto)
					AT2_DisableButton(AT2_UI_StartStop)
				end
			else
				AT2_DisableButton(AT2_UI_MessageMode_Auto)
			end			
			AT2_EnableEditBox(AT2_UI_MessageMode_MessageNum)
			
		else
			AT2_DisableButton(AT2_UI_StartStop)
			AT2_DisableEditBox(AT2_UI_TimedMode_Minutes)
			AT2_DisableEditBox(AT2_UI_TimedMode_Seconds)
			AT2_DisableButton(AT2_UI_TimedMode_Auto)
			AT2_DisableEditBox(AT2_UI_MessageMode_MessageNum)
			AT2_DisableButton(AT2_UI_MessageMode_Auto)
		end
end

function RGBToHex(r, g, b) -- © http://www.wowwiki.com/RGBToHex
AT2_Print("AT2CWR:"..r.." G:"..g.." B:"..b.."AT2CE","debug","RGBToHex")
	r = r <= 255 and r >= 0 and r or 0
	g = g <= 255 and g >= 0 and g or 0
	b = b <= 255 and b >= 0 and b or 0
	return string.format("%02x%02x%02x", r, g, b)
end

function AT2_UI_HandleModeCB(name)
for i=1,2,1 do
	getglobal("AT2_UI_MCB"..i):SetChecked(0)
	end
	name:SetChecked(1)
AT2_Mode = strsub(name:GetName(),11) -- 1 = időzített, 2 = üzenetenkénti mód
AT2_Print("AT2CWM: "..AT2_Mode.." ("..AT2_Mode:gsub("1","timed"):gsub("2","message")..") AT2CE","debug","UI_HandleModeCB")
end

function AT2_UI_HandleChannelCB(name)
	for i=1,6,1 do
	getglobal("AT2_UI_CCB"..i):SetChecked(0)
	end
	name:SetChecked(1)
	AT2_Channel=getglobal(name:GetName().."Text"):GetText()
	AT2_Print("Channel: "..AT2_Channel,"debug","HandleChannelCheckBox")
	if not(AT2_Channel == "Külsö") then AT2_DisableEditBox(AT2_UI_CustChanEditBox) else AT2_EnableEditBox(AT2_UI_CustChanEditBox) end
end

function AT2_UI_SetTimedModeEditBox(time_)
if (time_<60) then
AT2_UI_TimedMode_Seconds:SetText(time_);AT2_UI_TimedMode_Minutes:SetText(0)
else
AT2_UI_TimedMode_Minutes:SetText(floor((time_)/60));AT2_UI_TimedMode_Seconds:SetText(time_-(floor(time_/60)*60))
end
end

function AT2_RedYellowGreenNum(num,editbox)
AT2_Print("num:"..num, "debug","RedYellowGreenColorCoder")
if (editbox:GetText():gsub("\124cff9d9d9d",""):gsub("\124r","") == AT2_MessageEditBoxHelp or editbox:GetText():gsub("\124cff9d9d9d",""):gsub("\124r","") ==AT2_SavedMessageEditBoxHelp) then num = 0 end -- note: \124=|  c=color  ff=alpha,100% xx,yy,zz=r,g,b
	if (num < 100) then
		return "\124cff"..RGBToHex(num*2.5,255,0)..""..num.."\124r" 
	elseif (num >= 100 and num < 200) then
		return "\124cff"..RGBToHex(255,455-num*2.2222222,0)..""..num.."\124r"
	elseif (num > 225) then 
		return "\124cffFF0000"..num.."!\124r"
	else
		return "\124cffFF0000"..num.."\124r"
	end
end

function AT2_UI_InsertLink(text)
	if (AT2_UI_EditBox:HasFocus()) then
		AT2_UI_EditBox:Insert(text)
	elseif (AT2_UI_SavedMessages_EditBox:HasFocus()) then
		AT2_UI_SavedMessages_EditBox:Insert(text)
	end
end

function AT2_UI_AnimateResize(frame, width, height)
AT2_Print("called with "..frame:GetName().." "..width.." "..height,"debug","AnimResize")
	--if (not(AT2_isAnimatingResizing) and not(frame:GetHeight()==height) and not(frame:GetWidth()==width)) then
		AT2_Print("not animating, starting now","debug","AnimResize")
		AT2_isAnimatingResizing=true
		local origWidth,origHeight=tonumber(frame:GetWidth()),tonumber(frame:GetHeight())
		local f=f or CreateFrame("Frame")
		f:SetScript("OnUpdate",function() 
			AT2_Print("frame "..frame:GetName().." newWidth "..width.." newHeight "..height.." currWidth "..frame:GetWidth().." currHeight "..frame:GetHeight(),"debug","AT2_AnimResize -onupdate")
			if (((origHeight<=height and height<frame:GetHeight()) or (origHeight>=height and height>frame:GetHeight())) and ((origWidth<=width and width<frame:GetWidth()) or (origWidth>=width and width>frame:GetWidth()))) then 
				frame:SetWidth(width); frame:SetHeight(height);AT2_isAnimatingResizing=nil; AT2_Print("finishing animation, disposing onupdate (frame "..frame:GetName().." newWidth "..width.." newHeight "..height.." currWidth "..frame:GetWidth().." currHeight "..frame:GetHeight()..")","debug","AnimResize"); f:SetScript("OnUpdate",nil) 
			end
			if (origWidth<=width and width>frame:GetWidth()+1) then frame:SetWidth(frame:GetWidth()+1) elseif (origWidth>=width and width<frame:GetWidth()-1) then frame:SetWidth(frame:GetWidth()-1) end
			if (origHeight<=height and height>frame:GetHeight()+1) then frame:SetHeight(frame:GetHeight()+1) elseif (origHeight>=height and height<frame:GetHeight()-1) then frame:SetHeight(frame:GetHeight()-1) end
		end)
	--end
end

function AT2_UI_SetStatusBar(text, place)
	AT2_Print("text: "..tostring(text)..", place: "..tostring(place),"debug","AT2_UI_SetStatusBar")
	if (text == nil or text == "!clear") then
		AT2_UI_StatusTextLeft:SetText("")
		AT2_UI_StatusTextRight:SetText("")
		AT2_UI_StatusTextCenter:SetText("")
		--AT2_UI_AnimateResize(AT2_UI,AT2_UI:GetWidth(),116)
		AT2_UI:SetHeight(116)
	else
		if not(place==nil) then
			if (place:lower() == "l") then
				AT2_UI_StatusTextLeft:SetText(text)
				--AT2_UI_AnimateResize(AT2_UI,AT2_UI:GetWidth(),135)
			elseif (place:lower() == "r") then
				AT2_UI_StatusTextRight:SetText(text)
				--AT2_UI_AnimateResize(AT2_UI,AT2_UI:GetWidth(),135)
			end
		else
			AT2_UI_StatusTextCenter:SetText(text)
			--AT2_UI_AnimateResize(AT2_UI,AT2_UI:GetWidth(),135)
		end
		AT2_UI:SetHeight(135)
	end
end

function AT2_LoadUIObjectPositions()
	AT2_UI_ResizeHandler()
	AT2_UI_StatusTextCenter:SetWidth(456) 
	AT2_UI_CCB1:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT",56,21)
	for i=2,6,1 do
	getglobal("AT2_UI_CCB"..i):SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT",select(4,getglobal("AT2_UI_CCB"..(i-1)):GetPoint())+getglobal("AT2_UI_CCB"..(i-1).."Text"):GetStringWidth()+21,21)
	AT2_UI_CustChanEditBox:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT",select(4,getglobal("AT2_UI_CCB"..(i)):GetPoint())+getglobal("AT2_UI_CCB"..(i).."Text"):GetStringWidth()+25,20)
	end
	AT2_UI_TimedMode_Minutes:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT",select(4,AT2_UI_MCB1:GetPoint())+AT2_UI_MCB1:GetWidth()+5,39)
	AT2_UI_TimedMode_Minutes:SetWidth(32)
	AT2_UI_TimedMode_Seconds:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT",select(4,AT2_UI_TimedMode_Minutes:GetPoint())+AT2_UI_TimedMode_Minutes:GetWidth()+38,39)
	AT2_UI_TimedMode_Seconds:SetWidth(24)
	AT2_UI_Mins_Secs:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT", select(4,AT2_UI_TimedMode_Minutes:GetPoint())+AT2_UI_TimedMode_Minutes:GetWidth()+6,44)
	AT2_UI_TimedMode_Auto:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT", select(4,AT2_UI_Mins_Secs:GetPoint())+AT2_UI_Mins_Secs:GetWidth()+5,39)
	AT2_UIButtonAutoSize(AT2_UI_TimedMode_Auto)
	AT2_UI_MessageMode_MessageNum:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT", select(4,AT2_UI_MCB2:GetPoint())+AT2_UI_MCB2:GetWidth()+6,58)
	AT2_UI_MessageMode_MessageNum:SetWidth(36)
	AT2_UI_MessageMode_Messages:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT", select(4,AT2_UI_MessageMode_MessageNum:GetPoint())+AT2_UI_MessageMode_MessageNum:GetWidth()+6,63)
	AT2_UI_MessageMode_Auto:SetPoint("BOTTOMLEFT",AT2_UI,"BOTTOMLEFT", select(4,AT2_UI_MessageMode_Messages:GetPoint())+AT2_UI_MessageMode_Messages:GetWidth()+5,58)
	AT2_UIButtonAutoSize(AT2_UI_MessageMode_Auto)
	AT2_UI_CustChanEditBox:SetWidth(AT2_UI:GetWidth()-select(4,AT2_UI_CustChanEditBox:GetPoint()))
	
	AT2_UI_SettingsButton:SetPoint("TOPLEFT",AT2_UI,"TOPLEFT",1,-20)
	AT2_UI_ScriptsButton:SetPoint("LEFT",AT2_UI_SettingsButton,"RIGHT",2,0)
	AT2_UI_ReplacesButton:SetPoint("LEFT",AT2_UI_ScriptsButton,"RIGHT",2,0)
	AT2_UI_SavedMessagesButton:SetPoint("LEFT",AT2_UI_ReplacesButton,"RIGHT",2,0)
	AT2_UI_Vwhiteline1:SetPoint("TOPLEFT",AT2_UI_SettingsButton,"TOPRIGHT",1,0)
	AT2_UI_Vwhiteline2:SetPoint("TOPLEFT",AT2_UI_ScriptsButton,"TOPRIGHT",1,0)
	AT2_UI_Vwhiteline3:SetPoint("TOPLEFT",AT2_UI_ReplacesButton,"TOPRIGHT",1,0)
	AT2_UI_Vwhiteline4:SetPoint("TOPLEFT",AT2_UI_MessageMode_Auto,"TOPLEFT",-1,0)
	AT2_UI_Vwhiteline5:SetPoint("TOPLEFT",AT2_UI_TimedMode_Auto,"TOPLEFT",-1,0)
end

function AT2_LoadUIStrings()
AT2_UI_CCB1Text:SetText("Guild")
AT2_UI_CCB2Text:SetText("Yell")
AT2_UI_CCB3Text:SetText("Say")
AT2_UI_CCB4Text:SetText("Party")
AT2_UI_CCB5Text:SetText("Raid")
AT2_UI_CCB6Text:SetText("Külsö")
AT2_SendInterval=-1
AT2_SendMMInterval=-1
AT2_DisabledButtons = {}
AT2_TooltipStrings = {} -- "sima tooltipszöveg&letiltottgomb tooltipszöveg"
AT2_TooltipStrings["AT2_UI_StartStop_Activated"] = "Leállítja az automatikus küldést&Addig nem indíthatod el az automatikus küldést, amíg nem választottál ki egy csatornát, egy küldési módot, és annak a tulajdonságait!"
AT2_TooltipStrings["AT2_UI_StartStop"] = "Elindítja az automatikus küldést&Addig nem indíthatod el az automatikus küldést, amíg nem választottál ki egy csatornát, egy küldési módot, és annak a tulajdonságait!"
AT2_TooltipStrings["AT2_UI_TimedMode_Auto"]="A megadott csatornán 1 percig figyeli az üzenetek számát, és az alapján állít be egy időt.&Addig nem állíthatsz be időzített küldésre automatikusan időt, amíg nem választod ki ezt a módot, és nincs megadva egy csatorna!"
AT2_TooltipStrings["AT2_UI_MessageMode_Auto"]="A megadott csatornán 1 percig figyeli az üzenetek számát, és az alapján állít be egy üzenetsűrűséget.&Addig nem állíthatsz be üzenetenkénti küldésre automatikusan üzenetsűrűséget, amíg nem választod ki ezt a módot, és nincs megadva egy csatorna!"
AT2_TooltipStrings["AT2_UI_ScriptsButton"]="Különböző eseményekre különböző programokat írhatsz itt\nPl.: Automatikus leállítása egy bizonyos tartalmú privát üzenetkor, stb."
AT2_TooltipStrings["AT2_UI_VarsButton"]="Üzenetbe automatikusan behelyettesíthető szövegeket készíthetsz\nPl.: Tárgy darabszáma, idő egy időpontig, stb."
AT2_TooltipStrings["AT2_UI_SavedMessages_List"]="Megnyitja a mentett üzenetek listáját.&Nincs még egy mentett üzenet sem."
AT2_TooltipStrings["AT2_UI_SavedMessages_Delete"]="Törli a jelenleg kiválasztott mentett üzenetet.&Nincs kiválasztva mentett üzenet."
AT2_TooltipStrings["AT2_UI_SavedMessages_Insert"]="Beilleszti a fő szövegdobozba a jelenleg kiválasztott mentett üzenetet.&Nincs kiválasztva mentett üzenet."
AT2_TooltipStrings["AT2_UI_Replaces_List"]="Megnyitja a helyettesítések listáját.&Nincs még egy helyettesítés sem."
AT2_TooltipStrings["AT2_UI_Replaces_Delete"]="Törli a jelenleg kiválasztott helyettesítést.&Nincs kiválasztva helyettesítés."
AT2_TooltipStrings["AT2_UI_Replaces_Insert"]="Beilleszti a fő szövegdobozba a jelenleg kiválasztott helyettesítést.&Nincs kiválasztva helyettesítés."

end

function AT2_UI_ShowPreloads()
	Enigmatic:SetFont("Interface\\AddOns\\AutoTalker2\\Fonts\\Enigma__2.TTF",12,"OUTLINE") -- required for overriding Fontain (probably a bug in settings)
	Enigmatic_HL:SetFont("Interface\\AddOns\\AutoTalker2\\Fonts\\Enigma__2.TTF",12,"OUTLINE")
	Enigmatic_D:SetFont("Interface\\AddOns\\AutoTalker2\\Fonts\\Enigma__2.TTF",12,"OUTLINE")
	EnigmaticSmall:SetFont("Interface\\AddOns\\AutoTalker2\\Fonts\\Enigma__2.TTF",11,"")
AT2_LoadUIObjectPositions()
end

function AT2_UI_OtherUIPreload()
AT2_EnableButton(AT2_UI_SettingsButton)
AT2_EnableButton(AT2_UI_ScriptsButton)
AT2_EnableButton(AT2_UI_ReplacesButton)
AT2_EnableButton(AT2_UI_SavedMessagesButton)

--[[AT2_oldChatEditInsertLink = ChatEdit_InsertLink
ChatEdit_InsertLink = function(text)
    return AT2_UI_InsertLink(text) or AT2_oldChatEditInsertLink(text)
end]]

 -- Hook the container buttons
    local containerFunc = function(button)
        if IsShiftKeyDown() then
            if AT2_UI_EditBox:HasFocus() then
                AT2_UI_EditBox:Insert(GetContainerItemLink(button:GetParent():GetID(), button:GetID()))
            elseif AT2_UI_SavedMessages_EditBox:HasFocus() then
                AT2_UI_SavedMessages_EditBox:Insert(GetContainerItemLink(button:GetParent():GetID(), button:GetID()))
            end
        end
    end
    hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", containerFunc)

--bank
    -- Hook the bank buttons
    local bankFunc = function(button)
        if IsShiftKeyDown() then
            if AT2_UI_EditBox:HasFocus() then
                AT2_UI_EditBox:Insert(GetContainerItemLink(BANK_CONTAINER, button:GetID()))
            elseif AT2_UI_SavedMessages_EditBox:HasFocus() then
                AT2_UI_SavedMessages_EditBox:Insert(GetContainerItemLink(BANK_CONTAINER, button:GetID()))
            end
        end
    end
    hooksecurefunc("BankFrameItemButtonGeneric_OnModifiedClick", bankFunc)
    -- Hook the paper doll frame buttons
    local dollFunc = function(button)
        if IsShiftKeyDown() then
            if AT2_UI_EditBox:HasFocus() then
                AT2_UI_EditBox:Insert(GetInventoryItemLink("player", button:GetID()))
            elseif AT2_UI_SavedMessages_EditBox:HasFocus() then
                AT2_UI_SavedMessages_EditBox:Insert(GetInventoryItemLink("player", button:GetID()))
            end
        end
    end
    hooksecurefunc("PaperDollItemSlotButton_OnModifiedClick", dollFunc) 

	if IsAddOnLoaded("AutoTalker") then
		AT2_ShowMessageBox({ text="Az AutoTalker 1.X verziójának futtatása nem ajánlott a 2.0+ verzió mellett.",FrameToShowOn=AutoTalkerFrame,buttons={valami=function() print("hai") end},autoClose=false })
		AutoTalkerFrame:UnregisterAllEvents()
	end
end

function AT2_ShowMessageBox(data) -- reimplementing StaticPopup in own style
	AT2_UI_ShowPreloads() 
	AT2_MessageBoxCount=(AT2_MessageBoxCount or 0)+1
	local popup=CreateFrame("Frame","AT2_MessageBox"..AT2_MessageBoxCount,data.FrameToShowOn,"AT2_MessageBox")
	local reScale=function(num) return num+num*(1-GetCVar("UIScale")) end
	popup:SetWidth(data.FrameToShowOn:GetWidth())
	popup:SetHeight(data.FrameToShowOn:GetHeight())
	popup:SetBackdrop( {   bgFile = "Interface\\BUTTONS\\WHITE8X8",   edgeFile = "Interface\\BUTTONS\\WHITE8X8", tile = true, edgeSize = reScale(1),   insets = { left = 0, right = 0, top = 0, bottom = 0 } } )
	_G[popup:GetName().."_Text"]:SetFont("Interface\\AddOns\\AutoTalker2\\Fonts\\Enigma__2.TTF",reScale(12),"")
	_G[popup:GetName().."_Text"]:SetText(data.text)
	
	if (data.buttons) then
		local buttonCount=1
		for text,func in pairs(data.buttons) do
			buttonCount=buttonCount+1
		end
		local i=1
		for text,func in pairs(data.buttons) do
			local button=CreateFrame("Button",popup:GetName().."Button"..i,data.FrameToShowOn,"AT2Button")
			button:SetText(text)
			button:SetToplevel(true)
			button:SetWidth(((data.FrameToShowOn:GetWidth()/buttonCount)-buttonCount-1)*GetCVar("UIScale"))
			button:SetScale(reScale(GetCVar("UIScale")))
			button:SetPoint("BOTTOMLEFT",popup,"BOTTOMLEFT",popup:GetWidth()-(buttonCount*button:GetWidth()+reScale(1)),reScale(1))
			button:SetScript("OnClick",function() if not(data.autoClose==false) then popup:Hide() end RunScript(func) end)
			i=i+1
		end
	end
	
	popup:SetBackdropColor(0,0,0,0.65)
	popup:SetPoint("CENTER")
	popup:Show()
end

function AT2_Load()
AT2_UI:RegisterAllEvents() -- todo: not this
WorldFrame:HookScript("OnUpdate",AT2_UIHider)
AT2_UI:SetMinResize(486,205)
AT2_UI:RegisterForDrag("LeftButton","RightButton");
tinsert(UISpecialFrames, "AT2_UI")
AT2_LoadUIStrings()
AT2_LoadUIObjectPositions()
AT2_UI_ResizeHandler()
AT2_UI_OtherUIPreload()
AT2_UI_ParseSendMode()
AT2_UI:SetBackdropColor(0, 0, 0, 0.85)
AT2_MessageModeRemain=0
AT2_UI_Title:SetText("\124cff71D5FF\A\124r\124cff0070DD\uto\124r\124cff71D5FF\T\124r\124cff0070DDalker\124r\124cffFFFF33 "..GetAddOnMetadata("AutoTalker2","version").. " /ui-xml")
--AT2_AddEvent("CHAT_MSG_WHISPER","AT2_CheckWhisperToStopAutosend")


if not(AT2_ModuleList) then
AT2_ModuleList = {}
end
tinsert(AT2_ModuleList,"UI-xml");
end

if not(AT2_ModuleList) then
AT2_ModuleList = {}
end
tinsert(AT2_ModuleList,"UI-lua");
